﻿using System;
using System.Linq;
using System.Windows.Forms;

namespace Loader.Server {
    static class Program {

        static bool Is64BitProcess {
            get {
                //TODO: .NET 4.0 ve üstü için Environment.Is64BitProcess kullanılmalı.
                return IntPtr.Size == 8;
            }
        }

        [STAThread]
        static void Main(string[] args) {
            string arguments = "";
            string UpdateDirectory = "";
            string workDir = string.Empty;
            bool IsSaveimportantBackupFiles = false;
            string BackupCount = "";
            string BackupDirectoryName = "";
            if (args.Length > 0) {
                for (int i = 0; i < args.Length; i++) {
                    arguments += args[i] + " ";
                }
                workDir = arguments.Substring(0,arguments.Length-1);
            }
//#if DEBUG
//            System.Threading.Thread.Sleep(10000);
//#endif
            try {
                BackupCount = System.Configuration.ConfigurationSettings.AppSettings["BackupCount"].ToString();
                string[] UpdateFiles = System.Configuration.ConfigurationSettings.AppSettings["UpdateFiles"].ToString().Split(' ');
                BackupDirectoryName = System.Configuration.ConfigurationSettings.AppSettings["BackupDirectoryName"].ToString();
                string[] ImportantBackupFiles = System.Configuration.ConfigurationSettings.AppSettings["ImportantBackupFiles"].ToString().Split(' ');

                #region UpdateDirectory
                if (Is64BitProcess)
                    UpdateDirectory = System.Configuration.ConfigurationSettings.AppSettings["UpdateDirectory64"].ToString();
                else
                    UpdateDirectory = System.Configuration.ConfigurationSettings.AppSettings["UpdateDirectory"].ToString();
                bool relativePathUpdateDirectoryPath = true;
                if (UpdateDirectory.Length >= 3)
                    if (UpdateDirectory[1] == ':' && UpdateDirectory[2] == '\\') { //Bir sürücü ise c:\ gibi
                        relativePathUpdateDirectoryPath = false;
                    }
                if (UpdateDirectory.Length >= 2) {
                    if (UpdateDirectory[0] == '\\' && UpdateDirectory[1] == '\\') { // network adresi ise \\SqlCluster gibi
                        relativePathUpdateDirectoryPath = false;
                    }
                }

                if (relativePathUpdateDirectoryPath) {
                    if (UpdateDirectory.StartsWith("\\")) {
                        if (Application.StartupPath.EndsWith("\\")) {
                            UpdateDirectory = Application.StartupPath + UpdateDirectory.Substring(1);
                        } else {
                            UpdateDirectory = Application.StartupPath + UpdateDirectory;
                        }
                    } else {
                        if (Application.StartupPath.EndsWith("\\")) {
                            UpdateDirectory = Application.StartupPath + UpdateDirectory;
                        } else {
                            UpdateDirectory = Application.StartupPath + "\\" + UpdateDirectory;
                        }
                    }
                }
                #endregion
                int backupCountvalue;
                if (Int32.TryParse(BackupCount, out backupCountvalue)) {
                    if (!string.IsNullOrEmpty(UpdateDirectory) && System.IO.Directory.Exists(UpdateDirectory)) {
                        if (!string.IsNullOrEmpty(workDir) && System.IO.Directory.Exists(workDir)) {
                            if (!string.IsNullOrEmpty(BackupDirectoryName)) {
                                try {
                                    string[] files = System.IO.Directory.GetFiles(UpdateDirectory);
                                    if (files.Length > 0) {
                                        if (!System.IO.Directory.Exists(workDir + BackupDirectoryName))
                                            System.IO.Directory.CreateDirectory(workDir + BackupDirectoryName);
                                        string[] filesBackup = System.IO.Directory.GetDirectories(workDir + BackupDirectoryName);
                                        if (filesBackup.Length > backupCountvalue)
                                            System.IO.Directory.Delete(filesBackup[0]);
                                        foreach (string item in files) {
                                            if (UpdateFiles.Contains(item.Split('\\').Last())) {
                                                System.IO.FileInfo fileinfoserver = new System.IO.FileInfo(item);
                                                System.IO.FileInfo fileinfoClient = null;
                                                if (System.IO.File.Exists(workDir + item.Split('\\').Last()))
                                                    fileinfoClient = new System.IO.FileInfo(workDir + item.Split('\\').Last());
                                                if ((fileinfoClient == null && fileinfoserver.Exists) || (fileinfoClient != null && fileinfoClient.Exists && fileinfoserver.Exists && fileinfoserver.LastWriteTime != fileinfoClient.LastWriteTime)) {
                                                    if (!System.IO.Directory.Exists(workDir + BackupDirectoryName + "\\" + DateTime.Now.Date.ToString("yyyy-MM-dd")))
                                                        System.IO.Directory.CreateDirectory(workDir + BackupDirectoryName + "\\" + DateTime.Now.Date.ToString("yyyy-MM-dd"));
                                                    if (!IsSaveimportantBackupFiles && ImportantBackupFiles.Length > 0 && !string.IsNullOrEmpty(ImportantBackupFiles[0])) {
                                                        for (int i = 0; i < ImportantBackupFiles.Length; i++)
                                                            if (System.IO.File.Exists(workDir + ImportantBackupFiles[i]))
                                                                System.IO.File.Copy(workDir + ImportantBackupFiles[i], workDir + BackupDirectoryName + "\\" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "\\" + ImportantBackupFiles[i], true);
                                                        IsSaveimportantBackupFiles = true;
                                                    }
                                                    if (fileinfoClient != null && System.IO.File.Exists(fileinfoClient.FullName))
                                                        System.IO.File.Copy(fileinfoClient.FullName, workDir + BackupDirectoryName + "\\" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "\\" + item.Split('\\').Last(), true);
                                                    System.IO.File.Copy(fileinfoserver.FullName, workDir + item.Split('\\').Last(), true);
                                                }
                                            }
                                        }
                                    }
                                } catch (Exception e) { 
                                    MessageBox.Show(e.Message +" "+e.InnerException); }
                            } else
                                MessageBox.Show("Configdeki Backup Directory Name Bulunamadı!");
                        } else
                            MessageBox.Show("Working Directory Parametre Olarak Verilmeli Yada Adrese Erişilemiyor!");
                    } else
                        MessageBox.Show("Configdeki UpdateDirectory adresi Bulunamadı!");
                } else
                    MessageBox.Show("Configdeki BackupCount Rakam Olmalı!");
            } catch (Exception exe) { MessageBox.Show(exe.Message + " " + exe.InnerException); }
        }
    }
}
